package com.java.wx.filter;

import com.java.bean.Courier;
import com.java.bean.Message;
import com.java.bean.User;
import com.java.mvc.HandlerMapping;
import com.java.mvc.ResponseType;
import com.java.service.CourierService;
import com.java.service.UserService;
import com.java.util.UserUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter({"*.html", "*.do", "/"})
public class AccessControlFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        /*
            白名单： login.html  reg.html  /email/*  /admin/*  /log/*
            7天内可自动登录

         */
        HttpServletRequest req = (HttpServletRequest) request;
        final String uri = req.getRequestURI();
        if (uri.endsWith("login.html") || uri.endsWith("reg.html") || uri.startsWith("/email") || uri.startsWith("/admin") || uri.startsWith("/log")) {
            filterChain.doFilter(request, response);
            return;
        }
        final HttpServletResponse resp = (HttpServletResponse) response;

        // 先从session中获取用户
        User user = UserUtil.getUser(request);
        Courier courier = UserUtil.getCourier(request);
        if (user == null && courier == null) {
            // 如果没有获取到则未登录  从cookie中尝试自动登录
            Cookie[] cookies = req.getCookies();
            for (Cookie cookie : cookies) {
                if ("autoLogin".equals(cookie.getName())) {
                    String value = cookie.getValue();
                    if (!"false".equals(value)) {
                        user = UserService.getUserByEmail(value);
                        if (user != null) {
                            // 更新 cookie
                            Cookie cooki = new Cookie("autoLogin", value);
                            cooki.setPath("/");
                            cooki.setMaxAge(7 * 24 * 60 * 60);
                            resp.addCookie(cooki);
                            req.getSession().setAttribute("user", user);
                        } else {
                            courier = CourierService.getCourierByEmail(value);
                            if (courier != null) {
                                // 更新 cookie
                                Cookie cooki = new Cookie("autoLogin", value);
                                cooki.setPath("/");
                                cooki.setMaxAge(7 * 24 * 60 * 60);
                                resp.addCookie(cooki);
                                req.getSession().setAttribute("courier", courier);
                            }
                        }
                    }
                    break;
                }
            }
        }
        if (user != null) {
            if (uri.contains("expressAssist.html") || uri.contains("addExpress.html") || uri.contains("pickExpress.html") || uri.startsWith("/courier")) {
                resp.sendError(404, "很抱歉，这不是您该来的地方!");
            }
            filterChain.doFilter(request, response);
        } else if (courier != null) {
            filterChain.doFilter(request, response);
        } else {
            if (uri.endsWith(".do")) {
                final HandlerMapping.MVCMapping mvcMapping = HandlerMapping.get(uri);
                if (mvcMapping != null && mvcMapping.getType() == ResponseType.Text) {
                    resp.getWriter().write(new Message(-404, "请先登录").toJSON());
                    return;
                }
            }
            resp.sendRedirect("/login.html");
        }
    }

    @Override
    public void destroy() {

    }
}
